package com.delayqueue.core.common;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoUnit;

public class TimeUtil {

    private static DateTimeFormatter formatSecond = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter();
    private static DateTimeFormatter formatDate = new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd").toFormatter();


    public static LocalDateTime getLocalDateTime(long timeMillis) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), ZoneId.systemDefault());
    }

    public static String formatToDate() {
        return formatToDate(LocalDateTime.now());
    }

    public static String formatToDate(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return localDateTime.format(formatDate);
    }

    public static String formatToSecond() {
        return formatToSecond(LocalDateTime.now());
    }

    public static String formatToSecond(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            return null;
        }
        return localDateTime.format(formatSecond);
    }

    public static String format(String pattern) {
        return format(LocalDateTime.now(), pattern);
    }

    public static String format(LocalDateTime localDateTime, String patter) {
        if (localDateTime == null) {
            return null;
        }
        return localDateTime.format(new DateTimeFormatterBuilder().appendPattern(patter).toFormatter());
    }

    public static long getNextTime(long time, int changeNum, ChronoUnit chronoUnit) {
        Instant instant = Instant.ofEpochMilli(time);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        localDateTime = localDateTime.plus(changeNum, chronoUnit);
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }
}
